<template>
  <view class="body">
    <view class="date_top">
      <view class="date_btn" @tap="showCalendar">
        <text class="date">{{ isToday(state.today) }}</text>
        <image
          class="img_arrow"
          v-if="!state.datepickShow"
          src="https://ainengli.meilianshuke.com/jkhx/common/arrow_down.png"
        />
        <image
          class="img_arrow"
          v-if="state.datepickShow"
          src="https://ainengli.meilianshuke.com/jkhx/common/arrow_up.png"
        />
      </view>
    </view>
    <up-popup :show="state.dateShow" :round="16" mode="bottom" @close="closeCalendar">
      <uni-calendar
        :date="formatDate(state.today, 'yyyy-MM-dd')"
        :showMonth="false"
        :selected="state.dateSelects"
        :start-date="formatDate(state.yearsAgo, 'yyyy-MM-dd')"
        :end-date="formatDate(state.now, 'yyyy-MM-dd')"
        @change="setDate"
        @monthSwitch="getMouthDate"
      />
    </up-popup>
    <!-- </uni-datetime-picker> -->
    <view class="seven">
      <view
        v-for="(item, index) in state.weekList"
        :key="index"
        :class="['items', index == state.active ? 'active' : '']"
        @tap="selectDate(item, index)"
        >{{ item.label }}</view
      >
    </view>
    <view class="today_food">
      <image
        class="img_record"
        v-if="isToday(state.today) == '今天'"
        src="https://ainengli.meilianshuke.com/jkhx/common/foodRecord.png"
      />
      <view class="circle_progress">
        <zui-progress-circle
          :position="element.power.percent"
          :range="[270, 260]"
          :texture="[canEat < 0 ? '#ff503d' : '#00d1b6', '#f7f8fa']"
          :ringWidth="6"
          :size="120"
        />
        <view class="progress_flex">
          <view class="left_text">
            <view class="progress_has">已摄入</view>
            <view class="progress_num">{{ element.power.num }}</view>
          </view>
          <view class="center_text">
            <view class="progress_has">{{ canEat < 0 ? '多吃了' : '还可以吃' }}</view>
            <view class="progress_num">{{ canEat < 0 ? canEat * -1 : canEat }}</view>
            <view class="progress_has">推荐{{ element.power.recommend }}</view>
          </view>
          <view @tap="toSports" class="right_text">
            <view class="progress_has">运动消耗</view>
            <view class="progress_num">{{ element.power.sportConsumed }}</view>
          </view>
        </view>
      </view>
      <view class="element_list">
        <view class="element">
          <view class="title">
            <text class="title_name">碳水化合物</text>
            <!-- <text class="title_unit">g</text> -->
          </view>
          <progress
            :percent="element.carbon.percent"
            activeColor="#657EFF"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums"
            >{{ element.carbon.num.toFixed(1) }}/{{ element.carbon.recommend }}克</view
          >
        </view>
        <view class="element">
          <view class="title">
            <text class="title_name">蛋白质</text>
            <!-- <text class="title_unit">g</text> -->
          </view>
          <progress
            :percent="element.protein.percent"
            activeColor="#FF8450"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums"
            >{{ element.protein.num.toFixed(1) }}/{{ element.protein.recommend }}克</view
          >
        </view>
        <view class="element">
          <view class="title">
            <text class="title_name">脂肪</text>
            <!-- <text class="title_unit">g</text> -->
          </view>
          <progress
            :percent="element.fat.percent"
            activeColor="#63A1FF"
            :border-radius="100"
            stroke-width="4"
          />
          <view class="nums">{{ element.fat.num.toFixed(1) }}/{{ element.fat.recommend }}克</view>
        </view>
      </view>
    </view>
    <view v-if="mealInfo.length == 0" class="nodata">
      <image class="img_nodata" src="https://ainengli.meilianshuke.com/jkhx/noData.png" />
      <view class="nodata_text">还没有记录</view>
      <view class="nodata_text">请点击屏幕下方按钮来添加</view>
    </view>
    <!-- <view v-for="(i, idx) of tabList" :key="i">
      <view v-if="mealInfo[i]" class="meal_list">
        <view class="title">
          <text class="title_name">{{ i }}</text>
          <text class="title_power">已摄入{{ computeTotal((mealInfo[i] ? mealInfo[i] : [])) }}千卡</text>
        </view>
        <view class="meal_list_items">
          <view v-for="(item, index) of (mealInfo[i] ? mealInfo[i] : [])" :key="index" @tap="editFood(item, idx)" class="meal_list_item">
            <view class="name">{{ item.dietName }}</view>
            <view class="weight">{{ item.amount }}克</view>
            <view class="item_right">
              <view class="power">{{ item.energy }}千卡</view>
              <image class="img_more" src="https://ainengli.meilianshuke.com/jkhx/common/more.png" />
            </view>
          </view>
        </view>
      </view>
    </view> -->
    <view v-for="(i, idx) of mealInfo" :key="idx" class="meal_list">
      <view class="title">
        <text class="title_name">{{ i.dietType }}</text>
        <text class="title_power">已摄入{{ computeTotal(i.list) }}千卡</text>
      </view>
      <up-swipe-action ref="swipeRef">
        <up-swipe-action-item
          v-for="(item, index) of i.list"
          :key="index"
          :options="options"
          @click="handleClick(item, idx)"
        >
          <view class="meal_list_items">
            <view @tap="editFood(item)" class="meal_list_item">
              <view class="name">{{ item.dietName }}</view>
              <view class="weight">{{ item.amount }}克</view>
              <view class="item_right">
                <view class="power">{{ ((item.amount * item.energy) / 100).toFixed(0) }}千卡</view>
                <image
                  class="img_more"
                  src="https://ainengli.meilianshuke.com/jkhx/common/more.png"
                />
              </view>
            </view>
          </view>
        </up-swipe-action-item>
      </up-swipe-action>
    </view>
    <!-- 食物重量设置 -->
    <up-popup :show="state.setShow" :round="16" mode="bottom" closeable @close="close">
      <view class="food_info">
        <view class="title">
          {{ editInfo.date + ' ' + editInfo.foodInfo.dietType }}
        </view>
        <view class="info_top">
          <view class="name">{{ editInfo.foodInfo.dietName }}</view>
          <view class="power">{{ editInfo.foodInfo.energy }}千卡/100克</view>
        </view>
        <view class="info_detail">
          <view class="detail_item">
            <view class="text">热量</view>
            <view
              >{{
                (editInfo.foodInfo.energy * (editInfo.foodInfo.amount / 100)).toFixed(0)
              }}千卡</view
            >
          </view>
          <view class="detail_item">
            <view class="text">碳水化合物</view>
            <view
              >{{ (editInfo.foodInfo.cho * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
          <view class="detail_item">
            <view class="text">蛋白质</view>
            <view
              >{{ (editInfo.foodInfo.pro * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
          <view class="detail_item">
            <view class="text">脂肪</view>
            <view
              >{{ (editInfo.foodInfo.fat * (editInfo.foodInfo.amount / 100)).toFixed(1) }}克</view
            >
          </view>
        </view>
        <view class="input_info">
          <input
            type="digit"
            class="weight_input"
            :focus="state.tipFocus"
            :adjustPosition="false"
            :maxlength="4"
            @input="onInput"
            @keyboardheightchange="onKey"
            v-model="editInfo.foodInfo.amount"
          />
          <view class="unit">克</view>
          <view class="hot"
            >(热量约{{
              (editInfo.foodInfo.energy * (editInfo.foodInfo.amount / 100)).toFixed(0)
            }}千卡)</view
          >
        </view>
        <button class="submit" @tap="setConfirm">确定</button>
        <view class="bottom_box" :style="{ height: `${state.bottomHeight}rpx` }" />
      </view>
    </up-popup>
    <!-- 底部导航 -->
    <view class="tabs">
      <view class="tab" @tap="setFood('早餐')">
        <icon type="" class="iconfont icon-zaocan1 img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '早餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">早餐</text>
        </view>
      </view>
      <view class="tab" @tap="setFood('午餐')">
        <icon type="" class="iconfont icon-wufan img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '午餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">午餐</text>
        </view>
      </view>
      <view class="tab" @tap="setFood('晚餐')">
        <icon type="" class="iconfont icon-wanfan1 img_tab" />
        <view class="tab-icon">
          <text
            type=""
            v-if="mealInfo.findIndex((item) => item.dietType === '晚餐') != -1"
            class="iconfont icon-gouxuan img_finish"
          />
          <text v-else class="add">+</text>
          <text class="tab_text">晚餐</text>
        </view>
      </view>
      <view class="tab" @tap="state.show = true">
        <icon type="" class="iconfont icon-jiacan1 img_tab" />
        <view class="tab-icon">
          <text class="add">+</text>
          <text class="tab_text">加餐</text>
        </view>
      </view>
      <view class="tab" @tap="takePhoto">
        <icon class="iconfont icon-xiangji1 img_tab" />
        <view class="tab-icon">
          <text class="tab_text">拍照</text>
        </view>
      </view>
    </view>
    <up-popup :show="state.show" :round="16" mode="bottom" @close="state.show = false">
      <view class="lists">
        <view @tap="setFood('早加餐')" class="item">早加餐</view>
        <view @tap="setFood('午加餐')" class="item">午加餐</view>
        <view @tap="setFood('晚加餐')" class="item">晚加餐</view>
      </view>
      <view class="cancel" @tap="cancel">取消</view>
    </up-popup>

    <!-- 识别结果 -->
    <up-popup :show="resultShow" :round="16" mode="bottom" @close="resultShow = false">
      <view class="identify-info">
        <view class="title"> 识别结果 </view>
        <scroll-view @scroll="scroll" :scroll-top="scrollTop" scroll-y="true" class="scroll_view_style">
          <view class="identify-list">
            <view v-for="(item, index) of identifyList" :key="index" class="food_item">
              <view class="food_item_left">
                <view class="text">{{ item.foodName }}</view>
                <view>{{ item.calorie }}千卡/100克</view>
              </view>
              <view class="food_item_right">
                <input
                  type="digit"
                  :maxlength="4"
                  class="food-weight"
                  v-model="item.amount"
                />
                <text>克</text>
                <icon @tap="del(index)" class="iconfont icon-shanchu icon" />
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="record-list">
          <view @tap="selectShow = true" class="cell">
            <view class="left">记录日期</view>
            <view class="right">
              <view>{{ identifyDate }}</view>
              <image class="img_more" src="https://ainengli.meilianshuke.com/jkhx/common/more.png" />
            </view>
          </view>
          <view @tap="selectShow = true" class="cell">
            <view class="left">记录餐别</view>
            <view class="right">
              <view>{{ identifyType }}</view>
              <image class="img_more" src="https://ainengli.meilianshuke.com/jkhx/common/more.png" />
            </view>
          </view>
        </view>
        <view class="submit-box">
          <view class="submit-btn" @tap="save">保存</view>
        </view>
      </view>
    </up-popup>
    <up-picker 
      :show="selectShow" 
      :columns="columns" 
      @confirm="selectConfirm" 
      @cancel="selectShow = false"
      confirmColor="#00d1b6"
      ></up-picker>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { formatDate } from '@/utils/util'
import { throttle, deepCopy, debounce } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
import ZuiProgressCircle from '@/module/common/zui-progress-circle/zui-progress-circle.vue'
import {
  query_get_food,
  save_photo_food,
  update_food,
  delete_food,
  query_mouth_food,
  ai_recommend_food,
  pic_recognize_task,
  pic_recognize_result
} from '@/module/api/food'
import { base_info } from '@/api/moreMessage'
import store from '@/store'

const state = reactive({
  now: new Date(),
  yearsAgo: new Date().setFullYear(new Date().getFullYear() - 1),
  today: new Date(),
  datepickShow: false,
  dateShow: false,
  dateSelects: [],
  show: false,
  setShow: false,
  userInfo: {},
  active: 0,
  weekList: [],
  tipFocus: false,
  bottomHeight: 0,
  searchFocus: false,
  isSearch: false,
  searchValue: '',
  searchHistory: [],
  searchList: [],
  searchResults: []
})

const identifyList = ref([])
const columns = reactive([
  [],
  [
    '早餐',
    '午餐',
    '晚餐',
    '早加餐',
    '午加餐',
    '晚加餐',
  ]
])
const identifyDate = ref('')
const identifyType = ref('')

const options = reactive([
  {
    text: '删除',
    style: {
      backgroundColor: '#ff503d'
    }
  }
])
const swipeRef = ref()
const mealInfo = ref([])
const editInfo = reactive({
  date: '',
  type: '',
  foodInfo: {}
})
const element = reactive({
  power: {
    num: 0,
    recommend: 0,
    sportConsumed: 0,
    percent: 0
  },
  carbon: {
    num: 0,
    recommend: 0,
    percent: 100
  },
  protein: {
    num: 0,
    recommend: 0,
    percent: 100
  },
  fat: {
    num: 0,
    recommend: 0,
    percent: 100
  }
})

const resultShow = ref<boolean>(false)
const selectShow = ref<boolean>(false)
const scrollTop = ref(0)

const canEat = computed(() => {
  return element.power.recommend + element.power.sportConsumed - element.power.num
})

const urlParam = ref('')
let currentId = ''
onLoad((option) => {
  urlParam.value = option && option.empi ? option.empi : ''
  if (urlParam.value) {
    switchPatient(urlParam.value)
  }
})
onShow(() => {
  state.userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}
  currentId = urlParam.value ? urlParam.value : deepCopy(state.userInfo.patientInfo.empi)
  state.show = false // 加餐成功返回关闭加餐弹窗
  getTime()
  getData()
  const currentMouth = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1
  }
  getMouthDate(currentMouth)
  setOneMouth()
})
const switchPatient = (val) => {
  // 切换当前就诊人
  const params = {
    userId: JSON.parse(uni.getStorageSync('userInfo')).userId,
    empi: val
  }
  console.log('切换就诊人', params)
  base_info(params).then((res) => {
    const info = Object.assign({}, JSON.parse(uni.getStorageSync('userInfo')))
    info.patientInfo = res.data
    store.commit('SET_USERINFO', info)
    store.dispatch('im/IM_DISCONNECT')
  })
}

const showCalendar = () => {
  state.datepickShow = !state.datepickShow
  state.dateShow = !state.dateShow
}
const closeCalendar = () => {
  state.dateShow = false
  state.datepickShow = false
}

const setOneMouth = () => {
  columns[0] = []
  let nowDay = new Date().getTime()
  for(let i=0;i<31;i++) {
    columns[0].push(formatDate((nowDay - 86400000 * i), 'yyyy-MM-dd'))
  }
  columns[0][0] = '今天'
  columns[0][1] = '昨天'
  columns[0][2] = '前天'
}

const getData = () => {
  const params = {
    empi: urlParam.value ? urlParam.value : currentId,
    date: formatDate(state.today, 'yyyy-MM-dd')
  }
  query_get_food(params).then((res) => {
    mealInfo.value = res.data
    // 计算今日饮食总能量
    element.power.num = 0
    element.carbon.num = 0
    element.protein.num = 0
    element.fat.num = 0
    res.data.forEach((i) => {
      element.power.num += computeTotal(i.list)
      element.carbon.num += computeElement(i.list, 'cho')
      element.protein.num += computeElement(i.list, 'pro')
      element.fat.num += computeElement(i.list, 'fat')
    })
  })
  getAiData()
}
const getAiData = () => {
  // 获取今日推荐饮食
  const params = {
    empi: urlParam.value ? urlParam.value : currentId,
    recommendDate: formatDate(state.today, 'yyyy-MM-dd')
  }
  ai_recommend_food(params).then((res) => {
    if (res.data) {
      element.power.recommend = res.data.energy || 0
      element.carbon.recommend = res.data.cho
      element.protein.recommend = res.data.pro
      element.fat.recommend = res.data.fat
      element.carbon.percent = (element.carbon.num / element.carbon.recommend) * 100
      element.protein.percent = (element.protein.num / element.protein.recommend) * 100
      element.fat.percent = (element.fat.num / element.fat.recommend) * 100
      element.power.sportConsumed = res.data.sportConsumed || 0
      element.power.percent = (
        element.power.num /
        (element.power.recommend + element.power.sportConsumed)
      ).toFixed(2)
    }
  })
}
const getMouthDate = (e) => {
  e.month = Number(e.month)
  const mouthStart =
    (e.month == 1 ? e.year - 1 : e.year) + '/' + (e.month == 1 ? 12 : e.month - 1) + '/20'
  const mouthEnd =
    (e.month == 12 ? e.year + 1 : e.year) + '/' + (e.month == 12 ? 1 : e.month + 1) + '/15'
  const params = {
    empi: urlParam.value ? urlParam.value : currentId,
    start: formatDate(new Date(mouthStart), 'yyyy-MM-dd hh:mm:ss'),
    end: formatDate(new Date(mouthEnd), 'yyyy-MM-dd hh:mm:ss')
  }
  query_mouth_food(params).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.forEach((item) => {
        item.date = item.dietDate
        item.info = ''
      })
      state.dateSelects = res.data
    }
  })
}
const computeTotal = (arr: Array) => {
  // 计算热量
  let total = 0
  arr.forEach((item) => {
    total += Number(((item.energy * item.amount) / 100).toFixed(0))
  })
  return total
}
const computeElement = (arr: Array, type: string) => {
  // 计算营养素综合
  let total = 0
  arr.forEach((item) => {
    total += (item[type] * item.amount) / 100
  })
  return total
}

const getTime = () => {
  const day = state.today.getDay() === 0 ? 7 : state.today.getDay()
  state.weekList = getWeekDates()
  console.log(state.weekList, day)
  state.active = Number(day) - 1
  // state.weekList.forEach((item, index) => {
  //   if (day === 0) {
  //     state.active = 6
  //   }
  //   if (day == item) {
  //     state.active = index
  //   }
  // })
}

const getWeekDates = () => {
  const weekStringList = ['一', '二', '三', '四', '五', '六', '日']
  const now = state.today // 当前日期
  const currentDay = now.getDay() // 当前是周几（0 表示周日）
  const weekStart = new Date(now) // 当前周的第一天
  const weekDates: any = [] // 存储本周日期

  // 将周日调整为第 7 天（以周一为起始日）
  const adjustedDay = currentDay === 0 ? 7 : currentDay

  // 设置为本周周一
  weekStart.setDate(now.getDate() - adjustedDay + 1)

  for (let i = 0; i < 7; i++) {
    const weekDay = new Date(weekStart)
    weekDay.setDate(weekStart.getDate() + i)
    const formattedDate = `${weekDay.getFullYear()}-${(weekDay.getMonth() + 1)
      .toString()
      .padStart(2, '0')}-${weekDay.getDate().toString().padStart(2, '0')}`
    weekDates.push({ date: formattedDate, label: weekStringList[i] })
  }

  return weekDates
}

const selectDate = (data: any, index: number) => {
  state.active = index
  state.today = new Date(data.date)
  getData()
}
const isToday = (val) => {
  // 今天昨天前天转换
  const select = formatDate(val, 'yyyy/MM/dd') + ' 00:00:00'
  const today = formatDate(state.now, 'yyyy/MM/dd') + ' 00:00:00'
  if (new Date(today).getTime() - new Date(select).getTime() == 0) {
    return '今天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 86400000) {
    return '昨天'
  } else if (new Date(today).getTime() - new Date(select).getTime() == 172800000) {
    return '前天'
  } else {
    return formatDate(val, 'yyyy.MM.dd')
  }
}
const setDate = (e) => {
  state.datepickShow = false
  state.dateShow = false
  state.today = new Date(e.fulldate)
  getTime()
  getData()
}
const editFood = (val: any) => {
  const now = new Date(state.today)
  const date = now.getMonth() + 1 + '月' + now.getDate() + '日'
  editInfo.date = date
  editInfo.type = val.dietType
  editInfo.foodInfo = deepCopy(val)
  state.setShow = true
  setTimeout(() => {
    // 解决弹窗打开时，input无法获取焦点问题
    state.tipFocus = true
  }, 100)
}
const setConfirm = () => {
  if (!editInfo.foodInfo.amount || editInfo.foodInfo.amount == '0') {
    uni.showToast({
      title: '重量不能为0或空!',
      icon: 'error'
    })
    return
  }
  editInfo.foodInfo.dietDate = formatDate(state.today, 'yyyy-MM-dd')
  editInfo.foodInfo.amount = Number(editInfo.foodInfo.amount)
  update_food(editInfo.foodInfo).then((res) => {
    uni.showToast({
      title: '修改成功'
    })
    state.setShow = false
    state.tipFocus = false
    getData()
  })
}
const handleClick = (item: any, index: number) => {
  // 删除食物
  uni.showLoading()
  delete_food(item.id).then((res) => {
    uni.showToast({
      title: '删除成功'
    })
    uni.hideLoading()
    getData()
  })
  swipeRef.value[index].closeAll()
}
const setFood = (val: string) => {
  uni.navigateTo({
    url:
      '/module/src/pages/food/dailyFood/detail?food=' +
      val +
      '&date=' +
      formatDate(state.today, 'yyyy-MM-dd')
  })
}
const toSports = () => {
  uni.navigateTo({
    url: '/module/src/pages/sports/sportsInfo/index?today=' + formatDate(state.today, 'yyyy-MM-dd')
  })
}
const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - sys.safeAreaInsets.bottom * 2 - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = (e) => {
  if (e.detail.value * 1 > 3000) {
    editInfo.foodInfo.amount = 3000
  }
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}

const cancel = () => {
  state.show = false
}
const takePhoto = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sizeType: ['compressed'],
    success: (res) => {
      if (res.tempFiles[0].size > 1024 * 1024 * 10) {
        uni.showToast({
          title: '图片不能超过10MB',
          icon: 'none'
        })
      } else {
        let param = {
          empi: urlParam.value ? urlParam.value : currentId,
          path: res.tempFiles[0].tempFilePath
        }
        pic_recognize_task(param).then((res2) => {
          if (res2.code == 0 && res2.data) {
            identifyResult(res2.data.taskId)
          }
        })

      }
    },
    fail: (err) => {
      console.log('图片上传失败，原因：' + err)
    }
  })
}
const identifyResult = (id) => {
  uni.showLoading({
    title: '正在识别中...'
  })
  pic_recognize_result({taskId: id}).then((res3) => {
    if (res3.data.status == '2') {
      identifyList.value = res3.data.eatingItems
      identifyList.value.forEach((val) => {
        val.calorie = val.calorie.toFixed(0)
      })
      identifyDate.value = formatDate(state.today, 'yyyy-MM-dd')
      identifyType.value = getNowType()
      uni.hideLoading()
      resultShow.value = true
    } else if (res3.data.status == '1') {
      setTimeout(() => identifyResult(id), 1000)
    } else if (res3.data.status == '3') {
      uni.showToast({
        title: '未识别到食物',
        icon: 'none',
        duration: 2000
      })
    } else if (res3.data.status == '4') {
      uni.showToast({
        title: '识别失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
const save = () => {
  let hasAmount = true
  identifyList.value.forEach((item) => {
    if (!item.amount || item.amount == 0) {
      hasAmount = false
    }
    item.empi = urlParam.value ? urlParam.value : currentId
    item.dietDate = identifyDate.value
    item.dietType = identifyType.value
    item.dietCode = item.code
    item.energy = item.calorie
    item.pro = item.protein
    item.cho = item.carbohydrate
    item.dietName = item.foodName
  })
  if (hasAmount) {
    save_photo_food(identifyList.value).then((res) => {
      resultShow.value = false
      getData()
    })
  } else {
    uni.showToast({
      title: '食物重量不能为0或空',
      icon: 'none'
    })
  }
}
const selectConfirm = (e) => {
  console.log('确认选中', e)
  switch (e.value[0]) {
    case '今天':
      identifyDate.value = formatDate(state.now, 'yyyy-MM-dd')
      break
    case '昨天':
      identifyDate.value = formatDate(new Date(state.now).getTime() - 86400000, 'yyyy-MM-dd')
      break
    case '前天':
      identifyDate.value = formatDate(new Date(state.now).getTime() - 2 * 86400000, 'yyyy-MM-dd')
      break
    default:
      identifyDate.value = e.value[0]
      break
  }
  identifyType.value = e.value[1]
  selectShow.value = false
}
const getNowType = () => {
  const nowTimes = new Date()
  const hour = nowTimes.getHours()
  const minute = nowTimes.getMinutes()
  if (hour < 9) {
    return '早餐'
  }
  if (hour >= 19) {
    return '晚加餐'
  }
  if (hour >=16 && hour < 19) {
    return '晚餐'
  }
  if (hour >=14 && hour < 16) {
    return '午加餐'
  }
  if (hour == 9 || (hour == 10 && minute < 30)) {
    return '早加餐'
  }
  if ((hour > 10 && hour < 14) || (hour == 10 && minute >= 30)) {
    return '午餐'
  }
}

const del = (index) => {
  uni.showModal({
  	title: '警告',
  	content: '确定要删除吗？',
  	success: function (res) {
  		if (res.confirm) {
  			console.log('用户点击确定');
        identifyList.value.splice(index, 1);
        if (!identifyList.value.length) {
          resultShow.value = false
        }
  		} else if (res.cancel) {
  			console.log('用户点击取消');
  		}
  	}
  });
}
const scroll = debounce((e) => {
  scrollTop.value = e.detail.scrollTop
}, 200, '')
</script>

<style lang="scss" scoped>
.body {
  padding: 0 32rpx;
  padding-bottom: calc(156rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(156rpx + env(safe-area-inset-bottom));

  .date_top {
    text-align: center;

    .date_btn {
      box-sizing: border-box;
      display: inline-block;
      height: 60rpx;
      padding: 0 32rpx;
      margin: 24rpx auto;
      line-height: 60rpx;
      text-align: center;
      background: #fff;
      border-radius: 38rpx;

      .date {
        font-size: 28rpx;
        font-weight: 400;
        color: #222;
      }

      .img_arrow {
        width: 24rpx;
        height: 24rpx;
        margin-left: 16rpx;
      }
    }
  }

  .seven {
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    margin-bottom: 26rpx;

    .items {
      box-sizing: border-box;
      width: 77rpx;
      height: 76rpx;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 76rpx;
      color: #222;
      text-align: center;
      background: #fff;
      border-radius: 12rpx;
    }

    .active {
      color: #fff;
      background: #00d1b6;
    }
  }

  .today_food {
    position: relative;
    box-sizing: border-box;
    width: 686rpx;
    height: 428rpx;
    padding: 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .img_record {
      position: absolute;
      top: 0;
      left: 0;
      width: 192rpx;
      height: 44rpx;
    }

    .circle_progress {
      width: 100%;
      height: 240rpx;
      margin-bottom: 24rpx;

      .progress_flex {
        display: flex;
        justify-content: space-between;

        .center_text,
        .left_text,
        .right_text {
          width: 30%;
          margin-top: -180rpx;
          text-align: center;

          .progress_num {
            margin-bottom: 8rpx;
            font-size: 48rpx;
            font-weight: 600;
            color: #222;
          }

          .progress_has {
            font-size: 24rpx;
            font-weight: 400;
            color: #666;
          }
        }
      }
    }

    .element_list {
      display: flex;
      justify-content: space-between;
    }

    .element {
      width: 26%;

      .title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16rpx;

        .title_name {
          font-size: 28rpx;
          font-weight: 400;
          color: #222;
        }

        .title_unit {
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
        }
      }

      .nums {
        margin-top: 16rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
      }
    }
  }

  .nodata {
    text-align: center;

    .img_nodata {
      width: 320rpx;
      height: 240rpx;
      margin-top: 60rpx;
    }

    .nodata_text {
      font-size: 28rpx;
      font-weight: 400;
      color: #666;
    }
  }

  .meal_list {
    padding: 32rpx;
    margin-top: 24rpx;
    background: #fff;
    border-radius: 16rpx;

    .title {
      display: flex;
      align-items: center;

      .title_name {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }

      .title_power {
        margin-left: 16rpx;
        font-size: 22rpx;
        font-weight: 400;
        color: #999;
      }
    }

    .meal_list_items {
      ::v-deep .uni-swipe {
        margin-top: 24rpx;
      }

      ::v-deep .uni-swipe_button {
        font-size: 24rpx;
        font-weight: 400;
        color: #fff;
        border-radius: 0 12rpx 12rpx 0 !important;
      }

      .meal_list_item {
        position: relative;
        box-sizing: border-box;
        padding-bottom: 24rpx;
        margin-top: 24rpx;
        border-bottom: 1px solid #e5e6eb;

        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #333;
        }

        .weight {
          font-size: 28rpx;
          font-weight: 400;
          color: #999;
        }

        .power {
          margin-right: 16rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
        }

        .item_right {
          position: absolute;
          top: 30rpx;
          right: 0;
          display: flex;

          .img_more {
            width: 32rpx;
            height: 32rpx;
          }
        }

        &:last-child {
          padding-bottom: 0;
          border: none;
        }
      }
    }

    ::v-deep .u-swipe-action-item__right {
      top: 24rpx;
    }
  }

  .tabs {
    position: fixed;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 16rpx 64rpx;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #e5e6eb;

    .tab {
      .img_tab {
        margin-bottom: -8rpx;
        font-size: 48rpx;
        width: 48rpx;
        height: 48rpx;
      }

      .add {
        font-size: 20rpx;
        font-weight: 400;
        color: #666;
      }

      .img_finish {
        margin-right: 2rpx;
        font-size: 20rpx;
        width: 20rpx;
        height: 20rpx;
      }

      .tab_text {
        font-size: 20rpx;
        font-weight: 400;
        color: #666;
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;
    border: 1rpx solid #e5e6eb;

    .pre-btn {
      width: 35%;
      font-size: 32rpx;
      font-weight: 700;
      color: #00d1b6;
      background: #fff;
      border: 1rpx solid #00d1b6;
      border-radius: 44rpx;
    }

    .confirm-btn {
      width: 60%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;

      .img-logo {
        width: 32rpx;
        height: 32rpx;
        transform: translateY(4rpx);
      }
    }
  }

  ::v-deep .u-popup {
    .u-popup__content {
      overflow: hidden;
      // 设置重量弹窗
      .food_info {
        padding: 0 32rpx;

        .title {
          width: 100%;
          height: 104rpx;
          font-size: 30rpx;
          font-weight: 500;
          line-height: 104rpx;
          color: #333;
          text-align: center;
        }

        .info_top {
          .name {
            margin-bottom: 10rpx;
            font-size: 30rpx;
            font-weight: 500;
            color: #222;
          }

          .power {
            font-size: 28rpx;
            font-weight: 400;
            color: #666;
          }
        }

        .info_detail {
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          padding: 20rpx 38rpx;
          margin: 26rpx 0 30rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #999;
          border-top: 1rpx solid #e5e6eb;
          border-bottom: 1rpx solid #e5e6eb;

          .detail_item {
            flex: 1;
            text-align: center;

            .text {
              margin-bottom: 10rpx;
            }
          }
        }

        .input_info {
          position: relative;
          text-align: center;

          .weight_input {
            width: 200rpx;
            height: 84rpx;
            margin: 0 auto;
            font-size: 60rpx;
            font-weight: 500;
            color: #1cd7ae;
            border-bottom: 4rpx solid #1cd7ae;
          }

          .unit {
            position: absolute;
            top: 0;
            right: 235rpx;
            font-size: 24rpx;
            font-weight: 500;
            color: #1cd7ae;
          }

          .hot {
            margin-top: 16rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #666;
          }
        }

        .submit {
          width: 100%;
          height: 88rpx;
          padding: 0 !important;
          margin: 76rpx 0 32rpx;
          font-size: 32rpx !important;
          font-weight: 500;
          line-height: 88rpx !important;
          color: #fff;
          background: #00d1b6;
          border-radius: 50rpx;
        }
      }

      .questionaire-info {
        padding: 0;
        overflow: hidden;
        .title {
          width: 100%;
          height: 108rpx;
          font-size: 30rpx;
          font-weight: 600;
          line-height: 108rpx;
          color: #222;
          text-align: center;
          border-bottom: 1rpx solid #9aa3d3;
        }

        .questionaire-list {
          padding: 32rpx;
          height: calc(100vh - 350rpx);
          overflow: hidden auto;

          .cell {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 108rpx;
            background: #fafafa;
            border-radius: 16rpx;
            border: 1rpx solid #e5e6eb;
            margin-bottom: 24rpx;
            padding: 0 32rpx;

            .left {
              font-size: 30rpx;
              font-weight: 700;
              color: #222;
            }

            .right {
              display: flex;
              gap: 24rpx;
              justify-content: flex-end;
              font-size: 30rpx;
              font-weight: 400;
              color: #222;

              .form_input {
                text-align: right;
              }

              text {
                display: inline-block;
                width: 42rpx;
                text-align: left;
              }
            }
          }

          .user-item {
            height: 74rpx;
            background: #00d1b6;
            border-radius: 4rpx;
            .left {
              color: #fff;
            }
          }

          .topic_title {
            display: flex;
            align-items: center;
            margin-top: 40rpx;
            font-size: 32rpx;
            font-weight: 700;
            color: #222;
            justify-content: space-between;

            .tag {
              display: inline-block;
              padding: 4rpx 16rpx;
              margin-left: 8rpx;
              font-size: 24rpx;
              font-weight: 500;
              color: #fff;
              text-align: center;
              background: #5c8eff;
              border-radius: 4rpx;
            }

            .needlose {
              background: #ff813c;
            }
          }

          .search-input {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 100%;
            height: 84rpx;
            padding: 22rpx 24rpx;
            margin-top: 24rpx;
            font-size: 30rpx;
            font-weight: 400;
            line-height: 84rpx;
            color: #999;
            background: #fff;
            border: 2rpx solid #000;
            border-radius: 48rpx;
          }

          .allergy-foods {
            margin-top: 24rpx;

            .food-list {
              display: flex;
              flex-wrap: wrap;
              gap: 24rpx;
              justify-content: left;

              .foods-item {
                display: flex;
                align-items: center;
                height: 64rpx;
                padding: 0 16rpx;
                font-size: 28rpx;
                font-weight: 400;
                color: #00d1b6;
                background: rgb(0 209 182 / 10%);
                border-radius: 4rpx;
              }
            }
          }

          .topics {
            margin-top: 40rpx;

            .topic {
              width: 100%;
              height: 88rpx;
              padding-left: 32rpx;
              margin-bottom: 24rpx;
              font-size: 30rpx;
              font-weight: 400;
              line-height: 88rpx;
              text-align: left;
              background: #fafafa;
              border-radius: 8rpx;
            }

            .active {
              color: #00d1b6;
              background: rgb(0 209 182 / 5%);
              border: 1rpx solid #00d1b6;
            }

            .disabled {
              color: #ccc;
              background: #f5f5f5;
              border: 1rpx solid #e5e6eb;
            }
          }
          .img_more {
            width: 32rpx;
            height: 32rpx;
          }
        }
      }
      // 识别结果弹窗
      .identify-info {
        padding: 0;
        overflow: hidden;
        .title {
          width: 100%;
          height: 108rpx;
          font-size: 30rpx;
          font-weight: 600;
          line-height: 108rpx;
          color: #222;
          text-align: center;
          border-bottom: 1rpx solid #e5e6eb;
        }
        .scroll_view_style {
          max-height: calc(100vh - 688rpx);
          overflow-y: auto;
        }
        .identify-list {
          padding: 0 32rpx;
          // max-height: calc(100vh - 688rpx);
          // overflow-y: auto;
          .food_item {
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20rpx 0;
            margin: 26rpx 0 30rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #666;
            border-bottom: 1rpx solid #e5e6eb;
  
            .food_item_left {
              .text {
                color: #222;
                font-size: 30rpx;
                font-weight: 700;
                margin-bottom: 10rpx;
              }
            }
            .food_item_right {
              display: flex;
              align-items: center;
              .food-weight {
                width: 80rpx;
                text-align: center;
                background: #FAFAFA;
                border-radius: 4rpx;
                border: 1rpx solid #E5E6EB;
                font-weight: 500;
                font-size: 30rpx;
                color: #222222;
                padding: 12rpx 32rpx;
                margin-right: 16rpx;
              }
              .icon {
                margin-left: 16rpx;
                font-size: 40rpx;
              }
            }
          }
        }
        .record-list {
          padding: 32rpx;
          overflow: hidden auto;
          .cell {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 108rpx;
            background: #fafafa;
            border-radius: 16rpx;
            border: 1rpx solid #e5e6eb;
            margin-bottom: 24rpx;
            padding: 0 32rpx;

            .left {
              font-size: 30rpx;
              font-weight: 700;
              color: #222;
            }

            .right {
              display: flex;
              gap: 24rpx;
              justify-content: flex-end;
              font-size: 30rpx;
              font-weight: 400;
              color: #222;

              .form_input {
                text-align: right;
              }

              text {
                display: inline-block;
                width: 42rpx;
                text-align: left;
              }
              .img_more {
                width: 32rpx;
                height: 32rpx;
              }
            }
          }
        }
      }
      .submit-box {
        width: 100%;
        font-weight: 500;
        background: #ffffff;
        padding: 32rpx 24rpx;
        .submit-btn {
          width: 100%;
          height: 88rpx;
          background: #00d1b6;
          border-radius: 44rpx;
          color: #fff;
          font-weight: 600;
          font-size: 32rpx;
          text-align: center;
          line-height: 88rpx;
        }
      }

      // 加餐弹窗
      .lists {
        .item {
          height: 108rpx;
          font-size: 32rpx;
          font-weight: 400;
          line-height: 108rpx;
          color: #00d1b6;
          text-align: center;
          border-bottom: 1px solid #e5e6eb;
        }

        .item:last-child {
          border: none;
        }
      }

      .cancel {
        height: 108rpx;
        font-size: 32rpx;
        font-weight: 400;
        line-height: 108rpx;
        color: #222;
        text-align: center;
        border-top: 15rpx solid #f2f3f5;
      }

      .uni-calendar {
        .uni-calendar__header {
          .uni-calendar__header-text {
            font-size: 30rpx !important;
          }
        }

        .uni-calendar__box {
          .uni-calendar__weeks-day-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item__weeks-box-text {
            font-size: 30rpx !important;
          }

          .uni-calendar-item--isDay {
            border-radius: 8rpx;
          }
        }
      }
    }
  }

  .tab-icon {
    display: flex;
    align-items: center;
    margin-top: 8rpx;
  }

  ::v-deep .dialog-close {
    display: none;
  }

  ::v-deep .uni-calendar-item--isDay {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item--checked {
    background: #00d1b6;
  }

  ::v-deep .uni-date-editor {
    width: 254rpx;
    margin: 0 auto;
  }

  ::v-deep .uni-calendar-item--isDay-text {
    color: #00d1b6;
  }

  ::v-deep .uni-calendar-item--isDay .uni-calendar-item--isDay-text {
    color: #fff;
  }

  ::v-deep .uni-calendar-item__weeks-box-circle {
    background: #00d1b6;
  }

  ::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
    background-color: #00d1b6;
  }

  ::v-deep .uni-calendar__weeks-day {
    background: #ebfbf9;

    .uni-calendar__weeks-day-text {
      color: #00d1b6;
    }
  }

  ::v-deep .uni-datetime-picker--btn {
    height: 88rpx;
    line-height: 88rpx;
    background-color: #00d1b6;
  }

  ::v-deep .uni-progress-bar,
  ::v-deep .uni-progress-inner-bar {
    border-radius: 100rpx;
  }

  ::v-deep .u-icon__icon {
    top: 10rpx !important;
    font-size: 40rpx !important;
  }

  ::v-deep .search-input .u-icon__icon {
    top: 0 !important;
  }
}
</style>
